package com.jq.jqaicode.event.listener;


import com.jq.jqaicode.common.AppConstant;
import com.jq.jqaicode.common.file.CodeParserSaveTemplate;
import com.jq.jqaicode.common.file.WebScreenshot;
import com.jq.jqaicode.event.GenHtmlScreenshotEvent;
import com.jq.jqaicode.mapper.AiAppMapper;
import com.jq.jqaicode.model.entity.AiApp;
import com.jq.jqaicode.service.AiAppService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.io.File;


/**
 * 打印网站截图监听器
 *
 */
@Slf4j
@Component
class ScreenshotListener {

    @Autowired
    AiAppMapper aiAppMapper;

    @Value(value = "${web-screenshot.url}")
    private String web_url="";

    // 异步执行
    @Async
    @EventListener(classes = GenHtmlScreenshotEvent.class)
    public void onGenHtmlScreenshot(GenHtmlScreenshotEvent event) {
        String appId = event.getAppId();
        try {
            AiApp app = aiAppMapper.selectById(appId);
            String buildUniqueDir = CodeParserSaveTemplate.buildUniqueDir(app.getId(), app.getCodeGenType());
            String webUrl="";
            if("vue".equals(app.getCodeGenType())){
                buildUniqueDir=buildUniqueDir+ File.separator+"dist"+ File.separator;
                webUrl=web_url+"vue_"+app.getId()+"/dist/";
            }else{
                webUrl=web_url+"html_"+app.getId()+"/";
            }
            WebScreenshot.genHtmlScreenshot(webUrl,buildUniqueDir);
            app.setCover(webUrl+"homepage_screenshot.png");
            aiAppMapper.updateById(app);
            log.info("截图已保存，appId="+appId);
        } catch (Exception e) {
            // 记录失败，不影响主流程
            e.printStackTrace();
            log.info("截图保存失败："+e.getMessage());
        }
    }
}
